package Model;

import java.nio.ByteBuffer;
import java.util.Arrays;

public class PushAndPullMessage extends BaseMessage 
{
	private final int SIZE_OF_INT = 4;
	
	private byte[] m_PullToken;
	private byte[] m_Proof;
	private int m_Index;
	
	private byte[] m_PushToken;
	private byte[] m_Message;
	
	TokenManager manager;
	
	public PushAndPullMessage(byte[] request) 
	{	
		manager = TokenManager.getInstance();
	
		int startFrom = 0;
		
		// extract all from the message
		m_PullToken = Arrays.copyOfRange(request, startFrom, manager.getTokenLength());
		
		startFrom += manager.getTokenLength();
		
		byte[] tempForInt = Arrays.copyOfRange(request, startFrom, startFrom + SIZE_OF_INT);
		m_Index = ByteBuffer.wrap(tempForInt).getInt();
		
		startFrom += SIZE_OF_INT;
		
		m_Proof = Arrays.copyOfRange(request, startFrom, startFrom + manager.getProofLength());
		
		startFrom += manager.getProofLength();
		
		m_PushToken = Arrays.copyOfRange(request, startFrom, startFrom + manager.getTokenLength());
		
		startFrom += manager.getTokenLength();
		
		m_Message = Arrays.copyOfRange(request, startFrom, request.length);
	}
	
	@Override
	public byte[] pull() 
	{
		Data data = Data.getInstance();

		try
		{
			// validate proof and pull the data
			if (manager.isProofValid(m_Proof, m_PullToken))
			{		
				return build(eCode.Success, data.pull(m_PullToken, m_Index));
			}
		}
		catch(Exception e)
		{}
		
		return build(eCode.Error);
	}
	
	@Override
	public void push() 
	{
		// push the data
		Data data = Data.getInstance();
		data.push(m_PushToken,m_Message);
	}
}
